package com.camin.android;

import com.camin.android.db.IngredientTable;
import com.camin.android.utils.Constants;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class IngredientActivity extends BaseActivity {

	private Long ingredientId = null;
	private EditText etIngredientName;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.ingredient);

		etIngredientName = (EditText) findViewById(R.id.editIngredientName);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			ingredientId = extras.getLong(Constants.INGREDIENT_ID);
		}

		if (ingredientId != null) {
			// preload form with data
			Cursor cursor = getDataHelper().getIngredientById(getDatabase(), ingredientId);
			if (cursor.moveToFirst()) {
				etIngredientName.setText(cursor.getString(cursor
						.getColumnIndex(IngredientTable.ingredientName)));
			}
			cursor.close();
			getDatabase().close();
		}

		Button btnSaveIngredient = (Button) findViewById(R.id.btnSaveIngredient);
		btnSaveIngredient.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				ingredientId = saveIngredient();
				if (ingredientId != -1) {
					Intent data = new Intent();
					data.putExtra(Constants.INGREDIENT_ID, ingredientId);
					setResult(RESULT_OK, data);
				} else {
					setResult(RESULT_CANCELED);
				}
				finish();
			}
		});

		Button btnCancelIngredient = (Button) findViewById(R.id.btnCancelIngredient);
		btnCancelIngredient.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

	}

	private long saveIngredient() {
		long id = -1;

		ContentValues values = new ContentValues();
		values.put(IngredientTable.ingredientName, etIngredientName.getText()
				.toString());

		if (ingredientId == null) {
			id = getDataHelper().insertIngredient(
					getDataHelper().getWritableDatabase(), values);
		} else {
			getDataHelper()
					.updateIngredient(getDataHelper().getWritableDatabase(),
							values, ingredientId);
		}
		getDataHelper().close();
		return id;
	}

}
